package com.ac.config;

import com.base.annotation.DataEncrypt;
import com.base.helper.AesCrypt;
import com.base.helper.ClazzUtils;
import com.base.helper.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @Author mzl.
 */
@Aspect
@Component
public class DateEncryptAspect {

    private Logger logger = LoggerFactory.getLogger(DateEncryptAspect.class);

    private ThreadLocal<Long> startTime = new ThreadLocal<>();


    @Pointcut("execution(public * com.ac.api.*.service.impl.*.*(..))")
    public void dataEncrypt() {
    }

    @Before("dataEncrypt()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        Object[] args   = joinPoint.getArgs();
        Object   params = null;
        if (args != null && args.length > 0) {
            try {
                params = args[0];
            } catch (Exception e) {
                params = null;
            }
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        DataEncrypt dataEncrypt       = targetMethod.getAnnotation(DataEncrypt.class);
        if(null==dataEncrypt){
            return ;
        }
        String keyStr=dataEncrypt.params();
        if(StringUtils.isEmpty(keyStr)){
            return ;
        }
        List<String> keys       = Arrays.asList(keyStr.split(","));
        String[]     fieldNames = ClazzUtils.getFiledName(params);
        for (String fieldName : fieldNames) {
            if(keys.indexOf(fieldName)<0){
                continue;
            }
            String value = (String)ClazzUtils.getFieldValueByName(fieldName,params);
            value = AesCrypt.aesEncrypt(value);
            ClazzUtils.setFieldValueByName(fieldName,params,value);
        }
    }

}
